//
//  JCBarChart.m
//  JCBarCharts
//
//  Created by coollang on 17/2/27.
//  Copyright © 2017年 coollang. All rights reserved.
//

#import "JCBarChart.h"
#import "JCBarChartItem.h"

#define         WIDTH                 self.bounds.size.width
#define         HEIGHT                self.bounds.size.height

@interface JCBarChart ()<CAAnimationDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSMutableArray *bars;
@property (nonatomic, strong) NSMutableArray *describes;
@property (nonatomic, strong) UIView *tapCover;
@property (nonatomic, strong) CAGradientLayer *coverGradient;
@property (nonatomic, strong) UILabel *tapLabel;

@end

@implementation JCBarChart

//- (instancetype)initWithFrame:(CGRect)frame{
//    
//    if (self = [super initWithFrame:frame]) {
//        [self initUI];
//    }
//    return self;
//}
//
//- (instancetype)initWithCoder:(NSCoder *)aDecoder{
//    
//    if (self = [super initWithCoder:aDecoder]) {
//        [self initUI];
//    }
//    return self;
//}

- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    [self initUI];
}

- (void)initUI{
    
    if (_tapCover) {
        return;
    }
    self.backgroundColor = [UIColor clearColor];
    self.bars = [NSMutableArray array];
    self.describes = [NSMutableArray array];
    
    //画虚线
    for (NSInteger i = 0; i < 3; i++) {
        CAShapeLayer *dotteShapeLayer = [CAShapeLayer layer];
        CGMutablePathRef dotteShapePath =  CGPathCreateMutable();
        [dotteShapeLayer setFillColor:[[UIColor clearColor] CGColor]];
        [dotteShapeLayer setStrokeColor:[[[UIColor grayColor] colorWithAlphaComponent:0.6] CGColor]];
        dotteShapeLayer.lineWidth = 1.0f ;
        NSArray *dotteShapeArr = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:4],[NSNumber numberWithInt:6], nil];
        [dotteShapeLayer setLineDashPattern:dotteShapeArr];
        CGPathMoveToPoint(dotteShapePath, NULL, 0,(i+1)*((HEIGHT - 40)/4)+20);
        CGPathAddLineToPoint(dotteShapePath, NULL, WIDTH, (i+1)*((HEIGHT - 40)/4)+20);
        [dotteShapeLayer setPath:dotteShapePath];
        CGPathRelease(dotteShapePath);
        [self.layer addSublayer:dotteShapeLayer];
    }
    
    //X轴线
    UIBezierPath *coverPath = [UIBezierPath bezierPath];
    [coverPath moveToPoint:CGPointMake(0, HEIGHT-20)];
    [coverPath addLineToPoint:CGPointMake(WIDTH, HEIGHT-20)];
    CAShapeLayer *XLineLayer = [CAShapeLayer layer];
    XLineLayer.path = coverPath.CGPath;
    XLineLayer.lineWidth = 0.5f;
    XLineLayer.strokeColor = [kSeparationWhiteLineColor colorWithAlphaComponent:0.6].CGColor;
    XLineLayer.fillColor = [kSeparationWhiteLineColor colorWithAlphaComponent:0.6].CGColor;
    [self.layer addSublayer:XLineLayer];
    
    //点击覆盖层
    _coverGradient = [CAGradientLayer layer];
    [_coverGradient setColors:[NSArray arrayWithObjects:( __bridge id)[_barTapColor CGColor],(__bridge id)[_barTapColor CGColor], nil]];
    [_coverGradient setLocations:@[@0,@0.5]];
    [_coverGradient setStartPoint :CGPointMake (0.5,1)];
    [_coverGradient setEndPoint: CGPointMake(0.5,0)];
    _coverGradient.type = kCAGradientLayerAxial;
    
    [self addSubview:self.topLabel];
    [self addSubview:self.scrollView];
    
    self.scrollView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
    
    //默认值设置
    _barTapColor = [UIColor blueColor];
    _barColor = UIColorFromHex(0xBD8BFB);
    
    _tapCover = [UIView new];
    _tapCover.backgroundColor = _barTapColor;
}

- (void)setBarTapColor:(UIColor *)barTapColor{
    
    _barTapColor = barTapColor;
    _tapCover.backgroundColor = barTapColor;
}

- (void)setBarColor:(UIColor *)barColor{
    _barColor = barColor;
}

- (void)stroke{
    
    if (_scrollView == nil) {
        [self initUI];
    }
    
    _tapLabel.text = @"";
    self.topLabel.text = @"";
    
    for (UIView *bar in self.bars) {
        [bar removeFromSuperview];
    }
    [self.bars removeAllObjects];
    
    for (UILabel *label in self.describes) {
        [label removeFromSuperview];
    }
    [self.describes removeAllObjects];
    
    if (_items.count == 0) {
        return;
    }
    
    if (_items.count == 7) {
        _space = (WIDTH - 20*7) / 8.0;
        _barWidth = 20;
    }else if (_items.count == 4){
        _space = (WIDTH - 40*4) / 5.0;
        _barWidth = 40;
    }else if (_items.count == 5){
        _space = (WIDTH - 40*5) / 6.0;
        _barWidth = 40;
    }else if (_items.count == 12){
        _space = //(WIDTH - 20*12) / 13.0;
        _barWidth = WIDTH / 25.0;
    }
    
    CGFloat barWidth = _barWidth;
    CGFloat space = _space;
    CGFloat barCount = _items.count;
    CGFloat scrollHeight = HEIGHT - 20;
    CGFloat totalValue = scrollHeight - 35;
    CGFloat maxValue = [[[_items valueForKey:@"value"] valueForKeyPath:@"@max.floatValue"] floatValue];
    CGFloat scale = maxValue/totalValue;
    
    if (scale == 0) {
        return;
    }
    
    _scrollView.contentSize = CGSizeMake(space + _items.count * (space + barWidth), HEIGHT - 20);
    
    for (NSInteger i = 0; i < barCount; i++) {
        
        CGFloat barX = space + i*(barWidth + space);
        CGFloat describeLabelX = 0.5*space + i*(space + barWidth);
        CGFloat barHeigh = _items[i].value/scale;
        
        UIView *barView = [[UIView alloc] initWithFrame:CGRectMake(barX, scrollHeight-20 - barHeigh, barWidth, barHeigh)];
        barView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
        //切圆角
//        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, barWidth, barHeigh) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(barWidth/2, barWidth/2)];
//        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
//        maskLayer.frame = self.bounds;
//        maskLayer.path = maskPath.CGPath;
//        barView.layer.mask = maskLayer;
        barView.tag = i;
        
        [self.scrollView addSubview:barView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [barView addGestureRecognizer:tap];
        
        CAShapeLayer *line = [CAShapeLayer layer];
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(barWidth/2, barHeigh)];
        [path addLineToPoint:CGPointMake(barWidth/2, 0)];
        line.path = path.CGPath;
        line.cornerRadius = 3;
        line.lineWidth = barWidth;
        line.strokeColor = _barColor.CGColor;
        line.fillColor = _barColor.CGColor;
        [barView.layer addSublayer:line];
        
        CABasicAnimation *pathAnimation1 = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        pathAnimation1.duration = 0.3;
        pathAnimation1.delegate = self;
        pathAnimation1.fromValue = [NSNumber numberWithFloat:0.0f];
        pathAnimation1.toValue = [NSNumber numberWithFloat:1.0f];
        [line addAnimation:pathAnimation1 forKey:nil];
        
        [self.bars addObject:barView];
        
        UILabel *describeLabel = [[UILabel alloc] initWithFrame:CGRectMake(describeLabelX, scrollHeight - 10, barWidth + space, 10)];
        describeLabel.font = [UIFont systemFontOfSize:10];
        describeLabel.textColor = [UIColor lightGrayColor];
        describeLabel.textAlignment = NSTextAlignmentCenter;
        describeLabel.text = _items[i].key;
        describeLabel.adjustsFontSizeToFitWidth = YES;
        [_scrollView addSubview:describeLabel];
        [_describes addObject:describeLabel];
    }
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    
    //添加渐变色层
    for (NSInteger i = 0; i < _bars.count; i++) {
        //渐变色层设置
        UIView *barView = _bars[i];
        CAGradientLayer *gradient1 = [CAGradientLayer layer];
        gradient1.frame = barView.bounds;
        [gradient1 setColors:[NSArray arrayWithObjects:( __bridge id)[_barColor CGColor],(__bridge id)[_barColor CGColor], nil]];
        [gradient1 setLocations:@[@0,@0.5]];
        [gradient1 setStartPoint :CGPointMake (0.5,1)];
        [gradient1 setEndPoint: CGPointMake(0.5,0)];
        // 这个是使得颜色像素均匀变化（仅有一个选择）
        gradient1.type = kCAGradientLayerAxial;
        [barView.layer addSublayer:gradient1];
    }

}

- (void)tapAction:(UITapGestureRecognizer *)sender{
    
    UIView *barView = sender.view;
    NSInteger index = barView.tag;
    
    for (UILabel *label in _describes) {
        label.textColor = [UIColor lightGrayColor];
        label.font = [UIFont systemFontOfSize:10];
    }
    
    //渐变色层设置
    _coverGradient.frame = CGRectMake(0, 0, _barWidth, barView.bounds.size.height);
    [_tapCover.layer addSublayer:_coverGradient];
    
    _tapCover.frame = barView.bounds;
    _tapCover.transform = CGAffineTransformScale(_tapCover.transform, 1, 0.1);
    [barView addSubview:_tapCover];
    [UIView animateWithDuration:.2 animations:^{
        _tapCover.transform = CGAffineTransformIdentity;
    }];
    if ([self.delegate respondsToSelector:@selector(bar:didselected:)]) {
        [self.delegate bar:self didselected:barView.tag];
    }
    self.tapLabel.frame = CGRectMake(barView.frame.origin.x - 0.5*(_space - _barWidth), barView.frame.origin.y - 15, _space, 10);
    _tapLabel.text = @(_items[barView.tag].value).stringValue;
    [_scrollView addSubview:_tapLabel];
    
    UILabel *label = _describes[index];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:12];
    
//    self.topLabel.text = [NSString stringWithFormat:@"%@,%@h,%d拍",label.text,_tapLabel.text,arc4random()%2000];
     self.topLabel.text = [NSString stringWithFormat:@"%@,%@%@",label.text,_tapLabel.text,NSLocalizedString(@"Shot", nil)];
}

#pragma mark - 懒加载
- (UIScrollView *)scrollView{
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT - 20)];
        _scrollView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
    }
    return _scrollView;
}

- (UILabel *)topLabel{
    if (_topLabel == nil) {
        _topLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 20)];
        _topLabel.textAlignment = NSTextAlignmentCenter;
        _topLabel.font = [UIFont systemFontOfSize:10];
        _topLabel.textColor = [UIColor lightGrayColor];
    }
    return _topLabel;
}
- (UILabel *)tapLabel{
    
    if (_tapLabel == nil) {
        _tapLabel = [UILabel new];
        _tapLabel.font = [UIFont systemFontOfSize:10];
        _tapLabel.textColor = [UIColor whiteColor];
        _tapLabel.textAlignment = NSTextAlignmentCenter;
        _tapLabel.adjustsFontSizeToFitWidth = YES;
    }
    return _tapLabel;
}
@end
